package com.sinry.common.utils.redis;

import com.sinry.common.utils.Constant;
import org.springframework.cache.support.NullValue;

import java.util.concurrent.ThreadLocalRandom;
import java.util.function.Supplier;

public class CacheUtils {
    /**
     * 过期时间（秒）
     */
    public static final Long EXPIRED_SECONDS = Constant.EXPIRED_SECONDS;

    /**
     * 生成随机缓存时间（秒）
     */
    public static Long generateRandomCacheTime(Long origin, Long bound) {
        if (origin.equals(bound)) {
            return ThreadLocalRandom.current().nextLong(origin, bound + 300);
        }
        return ThreadLocalRandom.current().nextLong(origin, bound);
    }

    public static <R> R getList(String key, Supplier<R> dbFunc) {
        Object o = RedisTplUtils.ops(redis -> redis.opsForValue().get(key));
        if (isNull(o)) {
            o = dbFunc.get();

            RedisTplUtils.set(key, o, generateRandomCacheTime(EXPIRED_SECONDS, EXPIRED_SECONDS + 300));
        }
        return (R) o;
    }

    public static <R> R getOne(String key, Supplier<R> dbFunc) {
        Object o = RedisTplUtils.ops(redis -> redis.opsForValue().get(key));
        if (isNull(o)) {
            o = dbFunc.get();

            RedisTplUtils.set(key, o, generateRandomCacheTime(EXPIRED_SECONDS, EXPIRED_SECONDS + 300));
        }
        return (R) o;
    }


    /**
     * 是否空值
     *
     * @param object
     * @return
     */
    private static boolean isNull(Object object) {
        return object == null || object instanceof NullValue;
    }
}
